package com.servlet;

import com.entity.Shopingcar;
import com.mapper.ShopingcarMapper;
import com.util.MybatiesUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;


import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by webrx on 2017/6/22.
 */
@WebServlet("/shoping.do")
public class ShopingCar extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out =resp.getWriter();
        MybatiesUtil my = new MybatiesUtil();

        SqlSession ss= my.getSession();
        ShopingcarMapper car= ss.getMapper(ShopingcarMapper.class);

        String action= req.getParameter("action");


        System.out.println("**********");
        switch (action){
            case "add" :

                String id=req.getParameter("id")+"1006";
                Map<String,Object> map = new HashMap<String, Object>();

                map.put("bianhao",id);
                ss.commit();
              if(car.selectByBianHao(map).size()>0){

                  int num = car.updateCount(id);
                  ss.commit();
                  if(num>0){
                      out.print("恭喜您  ！  商品添加成功 。");
                  }

              }else {

                  String price = req.getParameter("price");
                  Double pp = Double.parseDouble(price);
                  String name = req.getParameter("name");


                  System.out.println(id + "####");
                  System.out.println(price);
                  System.out.println(name);

                  Shopingcar shop = new Shopingcar();
                  shop.setCarbianhao(id);
                  shop.setCarprice(pp);
                  shop.setCarname(name);
                  shop.setCarcount(1);
                  int nn = car.add(shop);
                  ss.commit();
                  if (nn > 0) {
                      out.print("恭喜您  ！  商品添加成功 。");
                  }

              }

                break;
            default:


                break;

        }
    }
}
